package com.aptemo.webetek.server.handlers;

import java.util.ArrayList;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.commands.impl.GetBetsAction;
import com.aptemo.webetek.client.commands.responses.ListResponse;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.server.data.WebetekUser;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.shared.BetBean;

public class BetsHandler
		extends ActionHandler<GetBetsAction, ListResponse<BetBean>>
{

	public BetsHandler(DataStoreAPI service)
	{
		super(service);
	}

	public Class<? extends Action<?>> getActionType()
	{
		return GetBetsAction.class;
	}

	@Override
	public ListResponse<BetBean> invoke(GetBetsAction action) throws BackendException, WebetekLoginException
	{
		utils.checkLogin();

		WebetekUser user = utils.getCurrentUser(action.getTeamId());
		if (user == null && !userService.isUserAdmin())
		{
			throw new BackendException(EErrorCodes.NOT_TEAM_MEMBER);
		}
		String userId = action.getUserId();

		if (userId == null || userId.isEmpty())
		{
			userId = user.getSid();
		}

		ArrayList<BetBean> result = (ArrayList<BetBean>) dataService.getBets(userId, action.getStatus());

		return new ListResponse<BetBean>(result);
	}
}
